/** 
 * Copyright (C), 2010-2012, AIYOU Software Co.,Ltd. ALL RIGHTS RESERVED. 
 * File name:RegLoginAction.java
 * Version:1.0
 * Date:Dec 17, 2011
 * Description: 
 * author:whh 
 */
package com.tietiao.action.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.tietiao.common.action.BaseAction;
import com.tietiao.common.constants.SysUserConstants;
import com.tietiao.common.util.SendEmailClient;
import com.tietiao.common.util.TietiaoUtil;
import com.tietiao.dao.model.SysUser;
import com.tietiao.dao.model.UserInvite;
import com.tietiao.service.sysuser.SysUserService;
import com.tietiao.service.userinvite.UserInviteService;

@Controller
@Scope("prototype")
public class UserAction extends BaseAction {
	private static final long serialVersionUID = -737414858771525004L;
	@Resource
	private SysUserService sysUserService;
	@Resource
	private UserInviteService userInviteService;
	private SysUser sysUser;
	private String validate;
	private String random;
	private String userName = "";
	private String password;
	// 登陆后跳回至页面
	private String fromUrl = "/friend_friends_home.htm";

	/**
	 * 功能：进入用户登陆首页面
	 * 
	 * @author: whh
	 * @Date: Dec 17, 2011
	 */
	public String index() {
		return DEFAULT;
	}

	/**
	 * 退出登陆，清空信息
	 * 
	 * @return
	 * @throws IOException
	 */
	public String toExit() throws IOException {
		request.getSession().removeAttribute(TietiaoUtil.SESSION_USER);
		TietiaoUtil.setCookies(response, null, "");
		return redirect("index_commodity_index.htm");
	}

	/**
	 * 跳转到登陆页面
	 * 
	 * @return
	 * @throws IOException
	 */
	public String toLogin() throws IOException {
		request.setAttribute("formUrl", fromUrl);
		SysUser user = getUser();
		if (fromUrl != null) {
			fromUrl = fromUrl.replace("$", "&");
		}
		// 如果已登陆或者cookies自动登陆
		if (user != null || TietiaoUtil.cookiesLogin(request, response)) {
			return redirect(fromUrl);
		} else {
			userName = userName == null ? TietiaoUtil.getStrByCookies(request,
					TietiaoUtil.COOKIE_USER_NAME) : userName;
		}
		TietiaoUtil.setToken(request);
		request.setAttribute("fromUrl", fromUrl);
		return DEFAULT;
	}

	/**
	 * 进入登陆页面
	 * 
	 * @return
	 * @throws IOException
	 */
	public String login() throws IOException {
		SysUser sysUser = sysUserService.loadSysUserByCodeOrEmail(userName);
		if (sysUser == null) {
			// 用户名不存在
			request.setAttribute("errorType", "1");
			request.setAttribute("userName", userName);
			return dispatcher("member_user_toLogin.htm");
		} else if (password.equals(sysUser.getPassword())) {
			if (request.getParameter("auto") != null) {// 设置cookie登陆
				TietiaoUtil.setCookies(response, userName, password);
			} else {
				TietiaoUtil.setCookies(response, userName, "");
			}
			request.getSession()
					.setAttribute(TietiaoUtil.SESSION_USER, sysUser);
			// 跳转到原先页面
			return redirect(fromUrl);
		} else {
			request.setAttribute("errorType", "2");
			return dispatcher("member_user_toLogin.htm");
		}
	}

	public String toFindPass() {
		TietiaoUtil.setToken(request);
		return DEFAULT;
	}

	public String findResult() {
		SysUser sysUser = sysUserService.loadSysUserByCodeOrEmail(userName
				.trim());
		request.setAttribute("operType", "findPass");
		if (sysUser != null) {
			Map<String, Object> para = new HashMap<String, Object>();
			para.put("name",
					sysUser.getRelName() == null ? sysUser.getPetName()
							: sysUser.getRelName());
			para.put("petName", sysUser.getPetName());
			para.put("password", sysUser.getPassword());
			boolean result = SendEmailClient.sendFindPass(sysUser.getEmail(),
					para);
			request.setAttribute("result", result);
		} else {
			request.setAttribute("result", false);
			request.setAttribute("message", "未找到相应的用户信息");
		}
		return dispatcher("/jsp/fg/global_result.jsp");
	}

	/**
	 * 
	 * 功能：注册输入界面。
	 * 
	 * @author: whh
	 * @Date: 2011-12-18
	 * 
	 * @return
	 */
	public String regInput() {
		TietiaoUtil.setToken(request);
		return DEFAULT;
	}

	/**
	 * 
	 * 功能：用户真实注册信息
	 * 
	 * @author: whh
	 * @Date: 2011-12-18
	 * @return
	 * @throws IOException
	 */
	public String reg() throws IOException {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		PrintWriter writer = response.getWriter();
		JSONObject object = new JSONObject();
		object.put("result", false);
		if (random.equalsIgnoreCase(TietiaoUtil.getRandom(request))) {
			UserInvite userInvite = userInviteService
					.getUserInviteByCode(validate.trim());
			if (userInvite != null) {
				System.out.println(sysUser);
				sysUser.setGender(SysUserConstants.GENDER_UNKNOW);
				sysUser.setCreateTime(new Date());
				sysUser.setState(1);
				sysUser.setIsActive(1);
				sysUser.setType(SysUserConstants.TYPE_USER);
				sysUser.setUserPhoto("/head/"+SysUserConstants.HEAD_UNKNOW);
				int result = sysUserService.insertSysUser(sysUser);
				if (result > 0) {
					TietiaoUtil.setSessionUser(request, sysUser);
					userInvite.setIsInvaild(1);
					userInviteService.updateUserInvite(userInvite);
					object.put("msg", "邀请码已过期，请重新获取！");
					object.put("result", true);
				} else {
					object.put("msg", "保存失败，稍后请重试！");
				}
			} else {
				object.put("msg", "邀请码不可用！");
			}
		} else {
			object.put("msg", "临时验证码,请刷新获取！");
		}

		writer.write(object.toString());
		writer.flush();
		writer.close();
		return null;
	}

	public String studyUse() {
		return dispatcher("/jsp/fg/member/user_reg_ok.jsp");
	}

	/**
	 * 
	 * 功能：异步验证昵称或者用户名存在与否
	 * 
	 * @author: whh
	 * @Date: 2011-12-18
	 * @return 返回json数组，result:true 是成功，其余失败
	 */
	public String validateUser() throws IOException {
		response.setContentType("text/html");
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter writer = response.getWriter();
		JSONObject object = new JSONObject();
		object.put("result", false);

		SysUser sysUser = sysUserService.loadSysUserByCodeOrEmail(validate);
		if (sysUser == null) {
			object.put("result", true);
		} else {
			SysUser sessionUser = getSysUser();
			if (sessionUser != null
					&& sysUser.getUserId() == sessionUser.getUserId()) {
				object.put("result", true);
			} else {
				object.put("message", "已存在");
			}
		}
		writer.write(object.toString());
		writer.flush();
		writer.close();
		return null;

	}

	public SysUser getSysUser() {
		return sysUser;
	}

	public void setSysUser(SysUser sysUser) {
		this.sysUser = sysUser;
	}

	public String getValidate() {
		return validate;
	}

	public void setValidate(String validate) {
		this.validate = validate;
	}

	public String getRandom() {
		return random;
	}

	public void setRandom(String random) {
		this.random = random;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setFromUrl(String fromUrl) {
		this.fromUrl = fromUrl;
	}

	public void setSysUserService(SysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}

	public UserInviteService getUserInviteService() {
		return userInviteService;
	}

	public void setUserInviteService(UserInviteService userInviteService) {
		this.userInviteService = userInviteService;
	}

	public String getUserName() {
		return userName;
	}

	public String getPassword() {
		return password;
	}

	public String getFromUrl() {
		return fromUrl;
	}

}
